package com.tanhua.server.service;

import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 评论管理-业务逻辑处理层
 */
@Service
@Slf4j
public class CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 评论列表查询
     */
    public PageResult<CommentVo> commentsList(Long page, Long pagesize, String movementId) {
        //1根据动态id分页查询评论表
        PageResult<Comment> commentPageResult = commentApi.commentsList(page, pagesize, movementId);
        if (commentPageResult == null || CollectionUtils.isEmpty(commentPageResult.getItems())) {
            return new PageResult<>(0l, 10l, 0l, 1l, null);
        }
        //2根据评论的作者id 批量获取用户信息
        List<Comment> commentList = commentPageResult.getItems();
        List<Long> listUserIds = commentList.stream().map(Comment::getUserId).collect(Collectors.toList());
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(listUserIds, null);

        //3基于评论数据和用户信息 构造Vo
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Comment comment : commentList) {
            commentVoList.add(CommentVo.init(userInfoMap.get(comment.getUserId()), comment));
        }
        //4返回分页Vo
        return new PageResult<>(page, pagesize, commentPageResult.getCounts(), commentVoList);
    }

    /**
     * 评论-提交
     */
    public void addComment(String movementId, String content) {
        //1 构造评论对象 调用服务提供者 发布评论内容
        //  a.（根据动态id查询动态表 获取被评论的用户id）
        //  b. (根据动态id更新动态表 评论数量+1)
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));//动态主键id
        comment.setCommentType(CommentType.COMMENT.getType());//评论类型：1-点赞，2-评论，3-喜欢
        comment.setContent(content);//评论内容
        comment.setUserId(UserHolder.getUserId());//评论人的用户id
        commentApi.add(comment);
    }
}
